<?php

namespace App\Admin\Metrics\ProjectDesc;

use Dcat\Admin\Admin;
use Dcat\Admin\Widgets\Metrics\Donut;
use App\Models\Cabinet;
use App\Models\DeviceType;
use App\Models\Project;
use App\Models\ProjectUser;

class DeviceCard extends Donut
{
    protected $labels = [];
    protected $labelsNum = 0;
    protected $data = [];
    protected $colors = [];

    /**
     * 初始化卡片内容
     */
    protected function init()
    {
        $this->getData();

        parent::init();

        $this->colors = array_slice($this->customColors, 0, $this->labelsNum);

        $this->title('设备类型');
        $this->chartLabels($this->labels);
        // 设置图表颜色
        $this->chartColors($this->colors);
        $this->contentWidth(5, 7);
        $this->height($this->labelsNum*20);
        $this->chartHeight($this->labelsNum*25 > 150 ? $this->labelsNum*25 : 150);
        $this->chartMarginTop($this->labelsNum*10);
        $this->chartMarginRight($this->labelsNum*4 > 50 ? $this->labelsNum*4 : 50);
    }

    protected function getData(){
        $projects = ProjectUser::where('user_id',Admin::user()->id)->pluck('projectId');
        $boxNum = Cabinet::whereIn('project_id',$projects)->where('pid', 0)->count();

        $this->labelsNum = 1;
        $this->labels[] = '云盒';
        $this->data[] = $boxNum;
    }

    /**
     * 渲染模板
     *
     * @return string
     */
    public function render()
    {
        $this->fill();

        return parent::render();
    }

    /**
     * 写入数据.
     *
     * @return void
     */
    public function fill()
    {
        $this->withContent();

        // 图表数据
        $this->withChart($this->data);
    }

    /**
     * 设置图表数据.
     *
     * @param array $data
     *
     * @return $this
     */
    public function withChart(array $data)
    {
        return $this->chart([
            'series' => $data,
            'dataLabels' => [
                'enabled' => true,
            ],
            'plotOptions' => [
                'pie' => [
                    'donut' => [
                        'size' => '75%',
                    ],
                ],
            ],
        ]);
    }

    /**
     * 设置卡片头部内容.
     *
     * @param mixed $desktop
     * @param mixed $mobile
     *
     * @return $this
     */
    protected function withContent()
    {
        $blue = Admin::color()->alpha('blue2', 0.5);

        $style = 'margin-bottom: 8px';
        $labelWidth = 120;

        $html = '';
        foreach ($this->labels as $k => $v) {
            $html .= '<div class="d-flex pl-1 pr-1 pt-1" style="'.$style.'"><div style="width: '.$labelWidth.'px"><i class="fa fa-circle" style="color: '.$this->colors[$k].'"></i>'.$v.'</div><div>'.$this->data[$k].'</div></div>';
        }

        return $this->content($html);
    }
}
